let App = getApp();
let time = require('../../utils/util.js');
var dateTimePicker = require('../../utils/dateTimePicker.js');
//截取最后一个后面的字符
function substringLast(str) {
  str = str.substring(0,str.length-1);
  return str
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    index:0,
    orderType:['待处理','待回访','待支付','已完成','已取消','待结算','已结算'],
    intention:['好','中','差'],
    classLevel: [],
    order:"",
    date:"",
    orderId:0,
    timeArray: null,
    visitTime: null,
    visitTimeIndex: [],
    freeTime: null,
    freeTimeIndex: [],
    isReturn:true,
    isShow:false,
    phone:'',
    isDis:true,
    hiddenmodalput:true,
    multiArray: [],
    regionData:[],
    regionIndex:0,
    typeIndex:1,
    refreIndex:1,
    reason:"",
    intentionIndex: 1, // 意向下拉默认索引
    classLevelIndex: 0, // 学车课程默认下拉索引
    remark:"",
    mobile:'',
    realName:'',
    params: {
      realname: '', // 姓名
      mobile: '', // 电话
      referer: '', // 来源
      area_id: '', // 地址 字符串
      intention:'',
      remark: '', // 备注
      pay_method: 3, // 支付方式 1=支付宝；2=微信；3=门店支付
      order_status: '', // 订单状态 1=未处理；2=待回访；3=待支付；4=已完成；5=已取消；6=待结算；7=已结算
    },
    paramsError: {
      realname: '请填写姓名', // 姓名
      mobile: '请填写电话号码', // 电话
      referer: '请选择来源', // 来源
      area_id: '请选择地区', // 地址 字符串
      intention:'请选择意向度',
      remark: '请填写备注', // 备注
      pay_method: 3, // 支付方式 1=支付宝；2=微信；3=门店支付
      order_status: '请选择订单状态', // 订单状态 1=未处理；2=待回访；3=待支付；4=已完成；5=已取消；6=待结算；7=已结算
    }
  },
  getRemark(){
    if(this.data.isShow == false ){
      this.setData({
        isShow:true
      })
    }else{
      this.setData({
        isShow:false
      })
    }
   
  },
  //选择订单状态e
  bindTypeChange:function(e){
    this.setData({
      typeIndex: e.detail.value
    })
  },

  //拨打电话
  callPhone(){
    wx.makePhoneCall({
      phoneNumber: this.data.phone //仅为示例，并非真实的电话号码
    })
  },
  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  //获取来源
  sourceList(){
    let that = this
    App._get(App.Domain+'Handler/Applet/getSource', {}, function (result) {
        if(result.code == 1){
          let multiArray = result.data
          that.setData({
            multiArray
          })
        }
    })
  },
  //获取地区
  regionList(){
    let that = this
    App._get(App.Domain+'Handler/Applet/getAllAreasByLoginUser', {}, function (result) {
        if(result.code == 1){
          let regionData = result.data
          that.setData({
            regionData
          })
        }
    })
  },
  //选择地区
  regionChange(e){
    this.setData({
      regionIndex: e.detail.value
    })
  },
  // 根据学校获取课程
  _getClassLevelBySchoolId(id){
    App._get(App.Domain+'Handler/Applet/getClassLevelBySchoolId', {schoolid: id}, (result) =>{
        if(result.code == 1){
          this.setData({
            classLevel: result.data
          })
        }
    })
  },
  formReset(e) {
    console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //日期选择
  bindDateChange: function(e) {
    const value = e.detail.value
    const { paramkey } = e.currentTarget.dataset
    const timeArray = this.data.timeArray
    const dateStr = `${substringLast(timeArray[0][value[0]])}-${substringLast(timeArray[1][value[1]])}-${substringLast(timeArray[2][value[2]])} ${substringLast(timeArray[3][value[3]])}:${substringLast(timeArray[4][value[4]])}`
    if(paramkey=='return_visit_time') {
      this.setData({
        visitTimeIndex: value,
      });
    }
    else {
      this.setData({
        freeTimeIndex: value
      });
    }
    const params = this.data.params
    params[paramkey] = dateStr
    this.setData({
      params
    })
  },
  changeDateTimeColumn(e) {
    const { paramkey } = e.currentTarget.dataset
    const dateArr = this.data.timeArray;
    if(paramkey=='return_visit_time') {
      let arr = this.data.visitTime
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]].replace("月", ''), '日');
      this.setData({
        visitTime: arr
      });
    }
    else {
      let arr = this.data.freeTime
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]].replace("月", ''), '日');
      this.setData({
        freeTime: arr
      });
    }
  },
  // 意向选择
  bindIntentionChange(e) {
    this.setData({
      intentionIndex: e.detail.value,
    })
  },
  // 来源
  bindclassLevelChange(e) {
    this.setData({
      refreIndex: e.detail.value
    })
  },
  // 姓名
  onBindName:function(e){
    this.setData({
      realName: e.detail.value
    })
  },
  // 手机号
  onBindMobile:function(e){
    this.setData({
      mobile: e.detail.value
    })
  },
  // 备注
  onBindRemark:function(e){
    this.setData({
      remark: e.detail.value
    })
  },
  // 提交
  submitConfirm() {
    const {multiArray,realName,mobile,remark, refreIndex ,regionData , params, paramsError, regionIndex , intention, intentionIndex, classLevel, classLevelIndex} = this.data
   
    params.order_status = parseInt(this.data.typeIndex)+1
    params.realname = realName
    params.mobile = mobile
    params.remark = remark
    params.intention = intention[intentionIndex]
    params.referer = multiArray[refreIndex]
    params.intention = intention[intentionIndex]
    params.area_id = regionData[regionIndex].id
    console.log('params',params)
    if(params.intention == '好'){
      params.intention = 1
    }else if(params.intention == '中'){
      params.intention = 2
    }else{
      params.intention = 3
    }
    for (const key in params) {
      if(key=='address') {
        continue
      }
      if(key=='free_time') {
        continue
      }
      if(typeof(params[key]) == 'string') params[key] = params[key].trim()
      if (!params[key]) {
        wx.showToast({
          icon:'none',
          title: paramsError[key]
        });
        return false;
      }
    }
    App._post(App.Domain+'Handler/Applet/addAdminOrder', params, function (result) {
      if(result.code == 1){
        wx.showToast({
          icon:'none',
          title: '新建成功'
        });
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },
  setDate() {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    // const {startYear, endYear} = this.data
    let dateNow = new Date();
    let year = dateNow.getFullYear();
    let month = dateNow.getMonth() + 1;
    month = month < 10 ? ('0'+month) : month
    let day = dateNow.getDate()
    day = day < 10 ? ('0'+day) : day
    let hour = dateNow.getHours()
    hour = hour < 10 ? ('0'+hour) : hour
    let minutes = dateNow.getMinutes();
    minutes = minutes < 10 ? ('0'+minutes) : minutes
    let startYear = year - 20
    let endYear = year + 20
    let defaultDate = `${year}年-${month}月-${day}日 ${hour}时:${minutes}分`
    var obj = dateTimePicker.dateTimePicker(startYear, endYear, defaultDate);
    this.setData({
      timeArray: obj.dateTimeArray,
      visitTimeIndex: obj.dateTime,
      freeTimeIndex: obj.dateTime,
    });
  },
  // 处理详情返回的时间参数，将其换算成正确的格式
  handleDateParmas(date, type) {
    if(type == 1) {
      date = new Date(parseInt(date))
    }
    else {
      date = new Date(date)
    }
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    month = month < 10 ? ('0'+month) : month
    let day = date.getDate()
    day = day < 10 ? ('0'+day) : day
    let hour = date.getHours()
    hour = hour < 10 ? ('0'+hour) : hour
    let minutes = date.getMinutes();
    minutes = minutes < 10 ? ('0'+minutes) : minutes
    return `${year}-${month}-${day} ${hour}:${minutes}`
  },
  onLoad: function (options) {
    let that = this
    that.sourceList()
    this.regionList()
  },
  cancelOrder(){
    this.setData({
      hiddenmodalput:false
    })
  },
  confirmM(){
  if(this.data.reason == ''){
    wx.showToast({
      title: '请填写取消原因',
      icon: 'none',
      duration: 2000
    })
  }else{
    let data = {
      order_id:this.data.orderId,
      cancel_reason:this.data.reason
    }
    App._post(App.Domain+'Handler/Applet/channelOrder', data, function (result) {
      if(result.code == 1){
        wx.navigateBack({
          delta: 1
        })
      }
    })
  }
},
cancelM(){
  this.setData({
    hiddenmodalput:true
  })
},
bindTextAreaBlur(e){
  this.setData({
    reason:e.detail.value
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})